package md5t

import (
	"crypto/md5"
	"encoding/hex"
	"hash"
	"io"
	"io/ioutil"
	"os"
)

//读取文件获得md5值
func Test(hhash hash.Hash, file *os.File, end, bufSize int) error {
	buf := make([]byte, bufSize)
	readLen := 0
	for {
		if readLen < end {
			n, err := file.Read(buf)
			if err != nil { //遇到任何错误立即返回
				if err == io.EOF { //忽略 EOF 错误信息
					break
				}
				return err
			}
			readLen += n
			hhash.Write(buf[:n]) //s, e := hhash.Write(buf[:n])
		}
	}
	return nil
}

//读取文件获得md5值
func GetFileMd5(file *os.File, bufSize int) (string, error) {
	buf := make([]byte, bufSize)
	m := md5.New()
	for {
		n, err := file.Read(buf)
		if err != nil { //遇到任何错误立即返回
			if err == io.EOF { //忽略 EOF 错误信息
				break
			}
			return "", err
		}
		m.Write(buf[:n]) //s, e := m.Write(buf[:n])
	}
	return hex.EncodeToString(m.Sum(nil)), nil // 输出加密结果
}

type FileMsg struct {
	FileNames   []string //文件名
	FolderNames []string //文件夹名
}

func New() *FileMsg {
	fm := &FileMsg{}
	return fm
}

//把文件或文件夹名称
//放入相应的slice
func (this *FileMsg) FMsg(scanDir string) {
	infos, err := ioutil.ReadDir(scanDir)
	if err == nil {
		for _, info := range infos {
			path := scanDir + "\\" + info.Name()
			if info.IsDir() {
				this.FolderNames = append(this.FolderNames, path)
				this.FMsg(path)
			} else {
				this.FileNames = append(this.FileNames, path)
			}
		}
	}
}
